<template>
  <div class="chat-container">
    <div class="chat-box">
      <div class="header">山东交通学院</div>
      <div class="content" v-html="content"></div>
      <div class="input-area">
        <el-input
          v-model="text"
          placeholder="请输入内容"
          type="textarea"
          maxlength="2000"
          rows="1"
          show-word-limit
        ></el-input>
        <div style="width: 20px"></div>
        <el-button type="primary" @click="send" style="margin-bottom: 20px"
          >发送</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
let socket;

export default {
  data() {
    return {
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      // user: {},
      // users: [],
      // chatUser: "管理员",
      text: "",
      // messages: [""],
      content: "",
    };
  },
  created() {
    this.init();
    this.loadChatLogs(); // 加载聊天记录
  },
  methods: {
    send() {
      if (!this.text) {
        this.$message({ type: "warning", message: "请输入内容" });
      } else {
        if (typeof WebSocket == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let timestamp = new Date().toISOString();
          let message = {
            from: this.$store.state.user.ybUserId,
            to: "",
            text: this.text,
            timestamp: timestamp,
          };
          socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端，由服务端进行转发
          // 构建消息内容，本人消息
          this.createContent(null, this.$store.state.user.ybUserId, this.text, timestamp);
          this.text = "";
        }
      }
    },
    loadChatLogs() {
      this.$http
        .get(`/chatlogs/${this.$store.state.user.ybUserId}`)
        .then((response) => {
          let chatLogs = response.data;
          chatLogs.forEach((log) => {
            let senderType = log.senderType;
            let message = log.message;
            let timestamp = log.timestamp;
            let senderId = log.senderId;
            let receiverId = log.receiverId;

            // 根据发送者类型确定消息应该显示在左边还是右边
            if (senderType === "parent") {
              this.createContent(null, senderId, message, timestamp);
            } else if (senderType === "admin") {
              this.createContent(senderId, null, message, timestamp);
            }
          });
        })
        .catch((error) => {
          console.error("Error fetching chat logs");
        });
    },
    createContent(remoteUser, nowUser, text, timestamp) {
      let html = "";
      let formattedTime = new Date(timestamp).toLocaleString();

      if (nowUser) {
        html = `
      <div class="message" style="padding: 5px 0;">
        <div class="time-text" style="text-align: right; padding-right: 10px">
          <div style="text-align: right; font-size: small; color: gray;">${formattedTime}</div>
          <div class="tip left" style="white-space: pre-wrap;">${text}</div>
        </div>
        <div class="name-avatar" style="text-align: center;margin-right:10px">
          <div style="font-size: small; color: black;">用户:${nowUser}</div>
          <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
            <img src="${this.circleUrl}" style="object-fit: cover;">
          </span>
        </div>
      </div>
    `;
      } else if (remoteUser) {
        html = `
      <div class="message2" style="padding: 5px 0">
        <div class="name-avatar" style="text-align: center;margin-right:10px">
          <div style="font-size: small; color: black;">管理员:${remoteUser}</div>
          <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
            <img src="${this.circleUrl}" style="object-fit: cover;">
          </span>
        </div>
        <div class="time-text" style="text-align: left;">
          <div style="text-align: left; font-size: small; color: gray;">${formattedTime}</div>
          <div class="tip right" style="white-space: pre-wrap;">${text}</div>
        </div>
      </div>
    `;
      }
      this.content += html;
    },
    init() {
      let userid = this.$store.state.user.ybUserId;
      let _this = this;
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = this.$socketBaseUrl + "/imserver/parent/" + userid;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data);
          let data = JSON.parse(msg.data);
          //  // {"from": "zhang", "text": "hello","timestamp":"xxx"}
          // 构建消息内容
          _this.createContent(data.from, null, data.text, data.timestamp);
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
  },
};
</script>

<style scoped>
.chat-container {
  width: 100vh;
  /* padding: 10px; */
  /* margin-bottom: 10px; */
}

.chat-box {
  margin: 0 auto;
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 0 20px #ccc;
}

.header {
  text-align: center;
  line-height: 50px;
}

.content {
  padding: 10px;
  background-color: #f9f6f6f2;
  height: 40vh;
  overflow: auto;
  border: 1px solid #f2f5f7;
  box-shadow: inset 0 0 30px #f2f5f7;
  border-radius: 10px;
  margin: 0px 20px 20px 20px;
}

.input-area {
  display: flex;
  justify-content: space-between;
  margin: 0 10%;
}

::v-deep .tip {
  color: white;
  text-align: left;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block !important;
}

::v-deep .right {
  background-color: deepskyblue;
}
::v-deep .left {
  background-color: forestgreen;
}
::v-deep .time-text {
  display: flex;
  flex-direction: column;
  display: inline-block !important;
  margin-right: 20px;
}
::v-deep .name-avatar {
  display: flex;
  flex-direction: column;
}
::v-deep .message {
  display: flex;
  justify-content: flex-end;
}
::v-deep .message2 {
  margin-left: 20px;

  display: flex;
  justify-content: flex-start;
}
</style>
